package com.example.course_mangger_system.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.course_mangger_system.entity.Course;
import com.example.course_mangger_system.mapper.CourseMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @description: 课程
 * @author: hyj
 * @date: 2023/11/25 15:59
 */
@Service
public class CourseService {

    @Resource
    private CourseMapper courseMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public int save(Course course) {
        int result = courseMapper.insert(course);

        // 更新缓存
        updateCache(course.getName()+course.getTeacherName());

        return result;
    }

    public int delete(Long id) {
        Course course = courseMapper.selectById(id);
        int result = courseMapper.deleteById(id);

        // 更新缓存
        updateCache(course.getName()+course.getTeacherName());

        return result;
    }

    public int update(Course course) {
        int result = courseMapper.updateById(course);

        // 更新缓存
        updateCache(course.getName()+course.getTeacherName());

        return result;
    }

    public List<Course> list(Course course) {
        String cacheKey = "course:" + course.getName()+course.getTeacherName();

        // 尝试从缓存中获取数据
        List<Course> cachedCourses = (List<Course>) redisTemplate.opsForValue().get(cacheKey);

        // 如果缓存中有数据，直接返回
        if (cachedCourses != null) {
            return cachedCourses;
        }

        // 如果缓存中没有数据，从数据库查询
        LambdaQueryWrapper<Course> queryWrapper = Wrappers.lambdaQuery(course);
        List<Course> courses = courseMapper.selectList(queryWrapper);

        // 将查询结果存入缓存，设置适当的过期时间
        redisTemplate.opsForValue().set(cacheKey, courses);

        return courses;
    }


    /**
     * 根据ID查询课程
     *
     * @param id
     * @return
     */
    public Course getById(Long id) {
        return courseMapper.selectById(id);
    }


    private void updateCache(String name) {
        String cacheKey = "course:" + name;

        // 清除缓存
        redisTemplate.delete(cacheKey);
    }
}